package com.service.oos;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletResponse;

import com.common.DateUtils;
import com.common.spring.SpringMvcUtils; 
import com.dao.oos.*;
import com.dao.sys.SysDeptMapper;
import com.model.oos.*;
import com.model.sys.SysDept;
import com.model.sys.SysUser;
import com.service.sys.WXService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import org.springframework.util.CollectionUtils;

@Service
public class OosDataService {
	static final Logger logger = LoggerFactory.getLogger(OosDataService.class);

	@Autowired
	OosDataDao oosDataDao;
	@Autowired
	OosItemService oosItemService;
	@Autowired
	OosItemDao oosItemDao;
	@Autowired
	OosExcutorsDao oosExcutorsDao;
	@Autowired
	OosTaskDao oosTaskDao;
	@Autowired
	OosImprovesDao oosImprovesDao;
	@Autowired
	OosTaskService oosTaskService;
	@Autowired
	OosImprovesService oosImprovesService;
	@Autowired
	SysDeptMapper sysDeptMapper;
	@Autowired
	WXService wxService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<OosDataModel> list = oosDataDao.selectList(queryMap);
		int count = oosDataDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String osId) {
		HttpResult httpResult = new HttpResult();
		OosDataModel oosDataModel = oosDataDao.load(osId);
		if (null != oosDataModel) {
			Map params = new HashMap();
			params.put("osId", osId);
			// 获取OOS异常项
			List<OosItemModel> oosItemModels = oosItemDao.selectItemListByOsId(osId);
			oosDataModel.setItemModelList(oosItemModels);
			// 获取OOS行动项
			List<OosTaskModel> taskModels = oosTaskDao.selectListByOsId(params);
			oosDataModel.setTaskModelList(taskModels);
			// 获取OOS整改措施列表
			List<OosImprovesModel> improvels = oosImprovesDao.selectListByOsId(params);
			oosDataModel.setOosImprovesModels(improvels);
		}

		httpResult.setData(oosDataModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 详情 为责任部门提供OOS数据详情查询功能
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInforDutyDept(String osId) {
		HttpResult httpResult = new HttpResult();
		OosDataModel oosDataModel = oosDataDao.load(osId);
		if (null != oosDataModel) {
			Map params = new HashMap();
			params.put("osId", osId);
			// 获取OOS异常项
			List<OosItemModel> oosItemModels = oosItemDao.selectItemListByOsId(osId);
			oosDataModel.setItemModelList(oosItemModels);
			// 获取OOS本责任部门行动项
			HttpResult taskResult = oosTaskService.selectListDutyDept(params);
			List<OosTaskModel> taskModels = null != taskResult.getData() ? (List<OosTaskModel>) taskResult.getData()
					: new ArrayList<>();
			oosDataModel.setTaskModelList(taskModels);
			// 获取本部门/个人的OOS整改措施列表
			HttpResult impsResult = oosImprovesService.selectListDutyDept(params);
			List<OosImprovesModel> improvels = null != impsResult.getData()
					? (List<OosImprovesModel>) impsResult.getData()
					: new ArrayList<>();
			oosDataModel.setOosImprovesModels(improvels);
		}

		httpResult.setData(oosDataModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存 目前OOS数据只能通过LIMS推送，不可手动新增
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult save(OosDataModel oosDataModel) throws IOException {
		if (oosDataModel == null) {
			return HttpResult.error("未从LIMS获取到OOS数据");
		}

		HttpResult httpResult = new HttpResult();
		if ("原料".equals(oosDataModel.getOsNoticeType())) {
			return HttpResult.ok("只接收产品OOS");
		}
		int result = 0;
		// 保存LIMS推送的OOS数据
		String oosId = UUID.randomUUID().toString();
		oosDataModel.setOsId(oosId);
		String osSampleCode = oosDataModel.getOsSampleCode();
		if (StringUtils.isNullOrEmpty(osSampleCode)) {
			return HttpResult.error("样品编码为空");
		}
		oosDataModel.setStatus("0");
		String osCode = createOOSCode();
		oosDataModel.setOsCode(osCode);
		String oosOrg = osSampleCode.substring(0, 2);
		oosDataModel.setOosOrg(oosOrg);
		result = oosDataDao.insert(oosDataModel);
		List<OosItemModel> oosItemModels = oosDataModel.getItemModelList();
		if (result > 0) {
			// 保存OOS异常数据
			int itemSave = 0;
			if (!CollectionUtils.isEmpty(oosItemModels)) {
				for (OosItemModel oosItemModel : oosItemModels) {
					oosItemModel.setOsId(oosId);
					oosItemModel.setItemId(UUID.randomUUID().toString());
					itemSave += oosItemDao.insert(oosItemModel);
				}
			}
			/**
			 * 新增行动项
			 */
			if (itemSave == oosItemModels.size()) {
				Map<String, Object> pars = new HashMap<>();
				pars.put("excDeptOrg", oosOrg);
				pars.put("excRole", "3");
				pars.put("excTaskFlag", "2");
				// 获取OOS管理人员
				List<OosExcutorsModel> oosManagers = oosExcutorsDao.selectList(pars);
				if (!CollectionUtils.isEmpty(oosManagers)) {
					for (OosExcutorsModel oosExcutorsModel : oosManagers) {
						// 发送OOS推送消息至企业微信
						// XY-推送给张东梅 司莎莎，SP-推送给杜政颜 孙宏杨
						wxService.sendTxtMessage(oosExcutorsModel.getExcAccount(), "【OOS提醒消息】有一条编号为 " + osCode + "的"
								+ oosDataModel.getOsSampleName() + "OOS数据推送，请前往CMP系统查看。");
					}
				}
				// 获取行动项接收人,默认为部门负责人
				pars.put("excRole", "1");
				pars.put("excTaskFlag", "1");
				List<OosExcutorsModel> excutors = oosExcutorsDao.selectList(pars);
				if (!CollectionUtils.isEmpty(excutors)) {
					for (OosExcutorsModel oosExcutorsModel : excutors) {
						// 发布行动项
						OosTaskModel oosTaskModel = new OosTaskModel();
						oosTaskModel.setOsId(oosId);
						oosTaskModel.setTaskId(UUID.randomUUID().toString());
						oosTaskModel.setExecutDeptCode(oosExcutorsModel.getDeptId());
						oosTaskModel.setDeptName(oosExcutorsModel.getDeptName());
						oosTaskModel.setExecutDeptName(oosExcutorsModel.getDeptName());
						oosTaskModel.setExecutName(oosExcutorsModel.getExcName());
						oosTaskModel.setExecutor(oosExcutorsModel.getExcAccount());
						oosTaskModel.setStatus("0");
						oosTaskModel.setDelFlag("0");
						oosTaskDao.insert(oosTaskModel);
						wxService.sendTxtMessage(oosExcutorsModel.getExcAccount(),
								"【OOS提醒消息】：您有一条OOS部门自查项待处理，编号：" + osCode + ",请在一小时内前往CMP系统查看处理。");
					}
				}
				httpResult.setMsg("保存成功!");
				httpResult.setData(oosDataModel);
			} else {
				httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
				httpResult.setMsg("保存失败!");
			}

		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败!");
		}
		return httpResult;
	}

	/**
	 * 更新OOS 品管部更新OOS主表、整改措施
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult update(OosDataModel oosDataModel) throws IOException {
		// wxUtil.sendTxtMessage("HI7199", "您好，本月工资10万已到账，请及时查收 !");
		if (null == oosDataModel) {
			return HttpResult.error("OOS数据为空");
		}
		if (StringUtils.isNullOrEmpty(oosDataModel.getOsId())) {
			return HttpResult.error("OOS主键为空");
		}
		String osId = oosDataModel.getOsId();
		int result = oosDataDao.update(oosDataModel);
		if (result > 0) {
			// 保存整改措施
			List<OosImprovesModel> oosImproves = oosDataModel.getOosImprovesModels();
			String osCode = oosDataModel.getOsCode();
			int impResult = 0;
			if (!CollectionUtils.isEmpty(oosImproves)) {
				for (OosImprovesModel oosImprovesModel : oosImproves) {
					String impId = oosImprovesModel.getImpId();
					String deptId = oosImprovesModel.getImpDutyDeptCode();
					// 根据deptId,获取该部门责任人
					Map<String, String> excutorInfor = oosDataDao.selectDeptByPrimaryKey(deptId);
					if (CollectionUtils.isEmpty(excutorInfor)) {
						return HttpResult.error("未查询到部门负责人信息，请联系管理员。");
					}
					// 若已存在，则更新
					if (StringUtils.isNotNull(impId)) {
						// 根据impId查询该条数据是否已经被责任部门维护过
						OosImprovesModel oosImprove = oosImprovesDao.load(impId);
						if (null != oosImprove) {
							// 前端传回的部门id与当前已存在的数据部门id不符合，表示已将该条数据的责任部门更换掉了
							if (!oosImprove.getImpDutyDeptCode().equals(oosImprovesModel.getImpDutyDeptCode())) {
								// 将原措施更新为已删除
								oosImprove.setDelFlag("1");
								oosImprovesDao.update(oosImprove);
								// 新增一条新部门的措施
								oosImprovesModel.setImpId(UUID.randomUUID().toString());
								// 执行人账号
								oosImprovesModel.setImpDutyPersonCode(excutorInfor.get("deptLeader"));
								oosImprovesModel.setImpDutyPersonName(excutorInfor.get("userName"));
								oosImprovesModel.setImpApprovelCode(excutorInfor.get("deptLeader"));
								oosImprovesModel.setImpApprovelName(excutorInfor.get("userName"));
								oosImprovesModel.setImpCompleteDescr("");
								oosImprovesModel.setImpRealTime(null);
								oosImprovesModel.setStatus(oosDataModel.getStatus());
								impResult += oosImprovesDao.insert(oosImprovesModel);
								// 如果status是提交，则不发送消息
								if (oosImprovesModel.getStatus().equals(Global.NO + "")) {
									wxService.sendTxtMessage(excutorInfor.get("deptLeader"),
											"【OOS提醒消息】：编号：" + osCode + "有您的一条待处理行动项，请在一小时内登录CMP处理。");
								}
							} else {
								// 若点击提交，则将各措施状态改为'1'
								if (oosDataModel.getStatus().equals(Global.YES + "")) {
									oosImprovesModel.setStatus("1");
								}
								impResult += oosImprovesDao.update(oosImprovesModel);
							}
						}
					} else {
						oosImprovesModel.setOsId(osId);
						oosImprovesModel.setImpId(UUID.randomUUID().toString());
						oosImprovesModel.setImpDutyPersonCode(excutorInfor.get("deptLeader"));
						oosImprovesModel.setImpDutyPersonName(excutorInfor.get("userName"));
						oosImprovesModel.setImpApprovelCode(excutorInfor.get("deptLeader"));
						oosImprovesModel.setImpApprovelName(excutorInfor.get("userName"));
						oosImprovesModel.setStatus(oosDataModel.getStatus());
						impResult += oosImprovesDao.insert(oosImprovesModel);
						if (oosImprovesModel.getStatus().equals(Global.NO + "")) {
							wxService.sendTxtMessage(excutorInfor.get("deptLeader"),
									"【OOS提醒消息】：编号：" + osCode + "有您的一条待处理行动项，请在一小时内登录CMP处理。");
						}
					}
				}
				if (impResult != oosImproves.size()) {
					return HttpResult.error("保存失败");
				}
			}
			// 如果是完成，则将该OOS下的行动项、整改措施改为1
			if (oosDataModel.getStatus().equals(Global.YES + "")) {
				oosTaskDao.updateCompleteByOsId(osId);
			}
		} else {
			return HttpResult.error("保存失败");
		}

		return HttpResult.ok("保存成功", this.selectInfor(osId).getData());
	}

	/**
	 * 更新OOS 此功能提供给各整改责任部门，修改OOS行动项与整改措施
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult updateForDutyDept(OosDataModel oosDataModel) throws IOException {
		if (null == oosDataModel) {
			return HttpResult.error("OOS数据为空");
		}
		if (StringUtils.isNullOrEmpty(oosDataModel.getOsId())) {
			return HttpResult.error("OOS主键为空");
		}
		OosDataModel oosDataTmp = oosDataDao.load(oosDataModel.getOsId());
		if (null == oosDataTmp || (Global.YES + "").equals(oosDataTmp.getStatus())) {
			return HttpResult.error("该OOS不存在或已完成，无需操作。");
		}

		String oosStatus = oosDataModel.getStatus();
		// 保存整改措施
		List<OosImprovesModel> oosImproves = oosDataModel.getOosImprovesModels();
		int impResult = 0;
		if (!CollectionUtils.isEmpty(oosImproves)) {
			for (OosImprovesModel oosImprovesModel : oosImproves) {
				if (oosStatus.equals(Global.YES + "")) {
					oosImprovesModel.setImpRealTime(DateUtils.getCurrentTime());
				} else {
					oosImprovesModel.setImpRealTime(null);
				}
				oosImprovesModel.setStatus(oosDataModel.getStatus());
				impResult += oosImprovesDao.update(oosImprovesModel);
			}
			if (impResult != oosImproves.size()) {
				return HttpResult.error("保存失败");
			}
		}
		// 保存行动项
		List<OosTaskModel> tasks = oosDataModel.getTaskModelList();
		int taskResult = 0;
		if (!CollectionUtils.isEmpty(tasks)) {
			for (OosTaskModel oosTaskModel : tasks) {
				oosTaskModel.setStatus(oosDataModel.getStatus());
				if (oosStatus.equals(Global.YES + "")) {
					oosTaskModel.setCommitTime(DateUtils.getCurrentTime());
				}
				taskResult += oosTaskDao.update(oosTaskModel);
			}
			if (taskResult != tasks.size()) {
				return HttpResult.error("保存失败");
			}
		}
		// 提交时，向OOS对应的OOS管理人发送企业微信消息
		if (oosStatus.equals(Global.YES + "")) {
			// 获取当前登录人的部门名称
			SysUser sysUser = SpringMvcUtils.getSysUser();
			SysDept sysDept = sysDeptMapper.selectByPrimaryKey(sysUser.getDeptid());
			Map<String, Object> pars = new HashMap<>();
			pars.put("excDeptOrg", oosDataModel.getOosOrg());
			pars.put("excRole", "3");
			pars.put("excTaskFlag", "2");
			// 获取OOS管理人员
			List<OosExcutorsModel> oosManagers = oosExcutorsDao.selectList(pars);
			if (!CollectionUtils.isEmpty(oosManagers)) {
				for (OosExcutorsModel oosExcutorsModel : oosManagers) {
					// 发送OOS推送消息至企业微信
					// XY-推送给张东梅 司莎莎，SP-推送给杜政颜 孙宏杨
					if (null != sysDept) {
						wxService.sendTxtMessage(oosExcutorsModel.getExcAccount(),
								"【OOS提醒消息】编号" + oosDataModel.getOsCode() + "，的OOS项目，" + sysDept.getDwmc()
										+ "已提交部门自查项或行动项内容，请前往CMP系统查看。");
					}

				}
			}
		}
		return HttpResult.ok("保存成功", oosDataModel);
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String osId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(osId)) {
			return HttpResult.error("参数不能为空");
		}
		int result = oosDataDao.delete(osId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 *
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<OosDataModel> list = oosDataDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), OosDataModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	public String createOOSCode() {
		String year = DateUtils.getCurrentYear();
		String month = DateUtils.getCurrentMonth();
		String queryparsm = year + "-" + month;
		int count = oosDataDao.queryCurrentOOSCount(queryparsm);
		AtomicInteger atomicInteger = new AtomicInteger(000);
		atomicInteger.addAndGet(count);
		int num = atomicInteger.incrementAndGet();
		// 补0
		DecimalFormat decimalFormat = new DecimalFormat("000");
		String serNum = decimalFormat.format(num);
		return "OOS-" + year + month + serNum;
	}
}
